package com.loginCheckMVC.servlet;

import com.loginCheckMVC.pojo.User;
import com.loginCheckMVC.service.UserService;
import com.loginCheckMVC.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //获取请求的数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        UserService userService = new UserServiceImpl();
        User user = userService.findUser(username, password);

        //判断user是否为null
        if (user != null) {
            //不为空 将user对象存储到域中
            request.getSession().setAttribute("user", user);

            //数据一致跳转到成功页面
            String contextPath = request.getContextPath();
            response.sendRedirect(contextPath + "/jsp/success.jsp");

        } else { // 为空跳转到登录
            //不一致跳转到登录页面
            System.out.println("用户名或密码错误！请重新输入。");

            //向域中存储message数据
            request.setAttribute("message", "用户名或密码错误！请重新输入。");

            //转发到登录页面
            request.getRequestDispatcher("/jsp/login.jsp").forward(request, response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
